using System.Linq.Expressions;

namespace Andshev.OrmTools.Linq2Query.Extensions
{
    public static class ExpressionExtensions
    {
        public static string ToSqlColumns<TDelegate>(this Expression<TDelegate> expression)
        {
            return
                CleanLambda(expression)
                    .RegexReplace("Convert\\(([^\\)])\\)", "$1")
                    .Replace("new []", string.Empty)
                    .CleanBrackets()
                    .Trim();
        }

        public static string ToSqlCondition<TDelegate>(this Expression<TDelegate> expression)
        {
            string sql = CleanLambda(expression);

            return sql
                .ChangeQuotes()
                .Replace(Constants.Cs.And, Constants.Sql.And)
                .Replace(Constants.Cs.Or, Constants.Sql.Or);
        }

        private static string CleanLambda<TDelegate>(Expression<TDelegate> expression)
        {
            string parameterClause = string.Empty;
            string parameterPrefix = string.Empty;

            if (expression.Parameters.Count > 0)
            {
                string parameter = expression.Parameters[0].Name;

                parameterClause = parameter + " => ";
                parameterPrefix = parameter + ".";
            }

            return expression.ToString()
                .Replace(parameterClause, string.Empty)
                .Replace(parameterPrefix, string.Empty);
        }
    }
}